// Created by lifei on 2020/6/1--11:45.

class DBL {
    keyName = "dbl-"

    constructor() {

    }

    /*
    * key:名称
    * value：内容
    * expire：过期时间，单位：秒，默认7天
    * */
    set(key, value, expire = 60 * 60 * 24 * 7) {
        let now = new Date().getTime()

        let content = ''
        switch (typeof value) {
            case 'string':
            case 'number':
            case 'boolean':
            case 'undefined':
                content = value
                break
            default:
                content = JSON.stringify(value)
                break
        }

        let data = {
            key: key,
            content: content,
            type: typeof value,
            expire: now + expire * 1000
        }
        sessionStorage.setItem(this.keyName + key, JSON.stringify(data))
    }

    get(key) {
        let value = sessionStorage.getItem(this.keyName + key)
        let now = new Date().getTime()
        let content
        if (value) {
            content = JSON.parse(value)
            if (content.expire < now) {
                content = null
                sessionStorage.removeItem(this.keyName + key)
            } else {
                switch (content.type) {
                    case 'string':
                        content = content.content
                        break

                    default:
                        content = JSON.parse(content.content)
                        break
                }
            }

        } else {
            content = null
        }
        return content
    }

    remove(key) {
        sessionStorage.removeItem(this.keyName + key)
    }
}

export default new DBL()
